package cn.zouchanglin.spider_xpu.utils;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

/**
 * URL编码工具
 * @author zouchanglin
 */
public class UrlEncodeUtils {
    /**
     * 默认汉字编码为 GB2312
     * @param url 需要编码的URL
     * @return 编码后的URL
     */
    public static String urlEncodeChinese(String url) throws UnsupportedEncodingException {
        char[] chars = url.toCharArray();
        StringBuilder sb = new StringBuilder();
        for(char ch: chars){
            if(ch >= '\u4e00' && ch <= '\u9fa5') sb.append(URLEncoder.encode(ch + "", "GB2312"));
            else sb.append(ch);
        }
        return sb.toString();
    }


    /**
     * 默认汉字编码为自定义编码
     * @param url 需要编码的URL
     * @param encoding 自定义编码（UTF-8、GBK、GB2312等）
     * @return 编码后的URL
     */
    public static String urlEncodeChinese(String url, String encoding) throws UnsupportedEncodingException {
        char[] chars = url.toCharArray();
        StringBuilder sb = new StringBuilder();
        for(char ch: chars){
            if(ch >= '\u4e00' && ch <= '\u9fa5') sb.append(URLEncoder.encode(ch + "", encoding));
            else sb.append(ch);
        }
        return sb.toString();
    }
}
